#include <iostream>
#include <unistd.h>
#include <vector>
#include <string>
#include <pthread.h>

pthread_cond_t cond = PTHREAD_COND_INITIALIZER; // 创建条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *MasterTask(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (true)
    {
        sleep(1);
        pthread_cond_signal(&cond); // 唤醒线程
        std::cout << "i'm" << name << std::endl;
    }
}

void *SlaverTask(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        std::cout << name << std::endl;
        pthread_mutex_unlock(&mutex);
    }
}

// 主控制线程启动
void StartMaster(std::vector<pthread_t> *tids)
{
    pthread_t tid;
    pthread_create(&tid, nullptr, MasterTask, (void *)"master Thread..."); // 不考虑创建失败
    tids->push_back(tid);                                                  // 将tid插入线程id管理数组，以便后续逐个进行等待
}

// 被控线程启动
void StartSlaver(std::vector<pthread_t> *tids, int num)
{

    for (int i = 0; i < num; i++)
    {
        char *name = new char[64];
        pthread_t tid;
        snprintf(name, 64, "Slaver Thread----%d!", i + 1);
        pthread_create(&tid, nullptr, SlaverTask, name);
        std::cout << name << "Start success...." << std::endl;
        tids->push_back(tid);
    }
}

// 等待所有线程
void WaitPthread(std::vector<pthread_t> &tids)
{
    for (auto tid : tids)
    {
        pthread_join(tid, nullptr);
    }
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "please enter right paramter!" << std::endl;
        return -1;
    }
    int num = std::stoi(argv[1]);
    std::vector<pthread_t> tids;
    // 控制主线程
    StartMaster(&tids);

    // 被控制的线程
    StartSlaver(&tids, num);

    // 等待所有线程
    WaitPthread(tids);
    return 0;
}